<?php

namespace app\recharge\model;

use app\recharge\model\Secret;
use think\Model;

/**
 * 订单号生成类
 */
class Order extends Model
{


    //自动写入时间戳
    protected $autoWriteTimestamp = 'timestamp';

    //自定义初始化
    protected function initialize()
    {
        //需要调用`Model`的`initialize`方法
        parent::initialize();
    }
    /**
     * 验证data
     *
     * @param  \think\Request  $request
     * @return   integer|false
     */
    public function checkData($param)
    {

        //判断$param['data'] 键名是否存在

        if (!array_key_exists('data', $param)) {

            $data = array(
                "code" => 1,
                "msg" => "'data' index don't exist",
                "data" => ['order_no' => ''],
            );

            //返回格式错误信息
            return ($data);
        }

        //判断$param['data'] 是否符合JSON规范

        if (!$this->isValidJson($param['data'])) {

            $data = array(
                "code" => 2,
                "msg" => $param['data'] . ' is not correct json format',
                "data" => ['order_no' => ''],
            );

            //返回格式错误信息
            return ($data);
        }

        //Json字符串转换数组

        $param = json_decode($param['data'], true);

        // serverid 键名存在

        if (!array_key_exists('serverid', $param)) {

            $data = array(
                "code" => 1,
                "msg" => "'serverid' index don't exist",
                "data" => ['order_no' => ''],
            );

            //返回格式错误信息
            return ($data);
        }

        // serverid 键值为空

        if (empty($param['serverid'])) {

            $data = array(
                "code" => 2,
                "msg" => "'serverid' is empty string",
                "data" => ['order_no' => ''],
            );

            //返回格式错误信息
            return ($data);
        }

        // rid 键名存在判断

        if (!array_key_exists('rid', $param)) {

            $data = array(
                "code" => 1,
                "msg" => "'rid' index don't exist",
                "data" => ['order_no' => ''],
            );

            //返回格式错误信息
            return ($data);
        }

        // rid 键值为空判断

        if (empty($param['rid'])) {

            $data = array(
                "code" => 2,
                "msg" => "'rid' is empty string",
                "data" => ['order_no' => ''],
            );

            //返回格式错误信息
            return ($data);
        }

        // product_type 键名存在判断

        if (!array_key_exists('product_type', $param)) {

            $data = array(
                "code" => 1,
                "msg" => "'product_type' index don't exist",
                "data" => ['order_no' => ''],
            );

            //返回格式错误信息
            return ($data);
        }

        // product_type 键值空判断

        if (empty($param['product_type'])) {

            $data = array(
                "code" => 2,
                "msg" => "'product_type' is empty string",
                "data" => ['order_no' => ''],
            );

            //返回格式错误信息
            return ($data);
        }

        return false;
    }

    /**
     * 验证sign数字签名
     *
     * @param  \think\Request  $request
     * @return   integer|false
     */
    public function checkSign($param)
    {

        //判断$param['sign'] 键名是否存在

        if (!array_key_exists('sign', $param)) {

            $data = array(
                "code" => 1,
                "msg" => "'sign' index don't exist",
                "data" => ['order_no' => ''],
            );

            //返回格式错误信息
            return ($data);
        }

        $sign = $param['sign'];
        $json = $param['data'];

        $record = Secret::getByApp_id('dragon_app');
        $secret = $record->app_secret;

        $verify = md5($json . $secret);
        $match = ($sign === $verify);

        if ($match) {

            $data = 0;

        } else {
            $data = array(
                "code" => 3,
                "msg" => "param's sign doesn't match",
                "data" => ['order_no' => ''],
            );
        }

        return ($data);
    }

    /**
     * 生成订单号
     *
     * @param  \think\Request  $request
     * @return   integer|false
     */
    public function createOrder($request)
    {

        //接收订单请求参数

        $param = $request->param();

        //验证发送来的data数据,如果发现错误返回错误信息

        $data = $this->checkData($param);

        if ($data) {
            return ($data);
        }

        //验证发送来的sign数据,如果发现错误返回错误信息

        $data = $this->checkSign($param);

        if ($data) {
            return ($data);
        }

        //Json字符串转换数组

        $param = json_decode($param['data'], true);

        //保存订单号：'s(服务器ID)-rid-商品类型ID-数据库自增ID'

        $order_no = $param['serverid'] . '-' . $param['rid'] . '-' . $param['product_type'];

        $param['order_no'] = $order_no;

        $this->isUpdate(false)->allowField(true)->save($param);

        //订单号附加自增ID

        $order_no = $order_no . '-' . $this->id;

        $data = [
            'id' => $this->id,
            'order_no' => $order_no,
        ];

        //更新订单号

        $this->isUpdate(true)->allowField(true)->save($data);

        $data = array(
            "code" => 0,
            "msg" => 'ok',
            "data" => ['order_no' => $order_no],
        );

        //返回新订单号
        return ($data);
    }

    /**
     * 判断是否是有效的Json字符串数据。
     */
    public function isValidJson($strJson)
    {
        json_decode($strJson);
        return (json_last_error() === JSON_ERROR_NONE);
    }

    /**
     * 列表(主键列表，条件数组，闭包查询)
     *
     * @param    array $param 查询条件
     * @return   void
     */
    public function doList($param = null)
    {

        try {

            //查询数据
            $result = self::all($param);
            $rows = [];

            foreach ($result as $data) {
                $item = $data->getData();
                array_push($rows, $item);
            }

            //返回结果
            $res = array();

            $total = count($rows);

            if ($total > 0) {
                $res['rows'] = $rows;
                $res['total'] = $total;
            } else {
                $res['total'] = 0;
                $res['rows'] = array();
            }

            //请求类型返回
            return ($res);

        } catch (\Exception $e) {
            throw new \think\Exception('异常消息:' . $e->getMessage());
        }
    }
}
